package org.devlabs35.javamail;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;

public class ReceiveMailPOP3 {
	private static final String HOST = "localhost";
	private static final String USERNAME = "sairam35@devlabs.mail.org";
	private static final String PASSWORD = "sairam35";

	public static void doit() throws MessagingException, IOException {
		Folder folder = null;
		Store store = null;
		try {
			Properties props = new Properties();
			props.put("mail.store.protocol", "pop3");
			Session session = Session.getDefaultInstance(props);
			// session.setDebug(true);
			store = session.getStore();
			store.connect(HOST, USERNAME, PASSWORD);
			folder = store.getDefaultFolder().getFolder("INBOX");
			folder.open(Folder.READ_ONLY);
			Message[] messages = folder.getMessages();
			System.out.println("No of Messages : " + folder.getMessageCount());
			System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
			for (int i = 0; i < messages.length; ++i) {
				System.out.println("MESSAGE #" + (i + 1) + ":");
				Message msg = messages[i];
				Enumeration headers = msg.getAllHeaders();
				System.out.println("Print all email headers:########START#######");
				while (headers.hasMoreElements()) {
					Header h = (Header) headers.nextElement();
					System.out.println("---" + h.getName() + ": " + h.getValue());
				}
				System.out.println("Print all email headers:########END########");
				System.out.println("Msg Disposition :" + msg.getDisposition());
				System.out.println("Content:" + msg.getContent());

				System.out.println("Content Type:" + msg.getContentType());
				Multipart multiMsg = (Multipart) msg.getContent();
				System.out.println("Count : " + multiMsg.getCount());

				System.out.println("Body part :" + multiMsg.getBodyPart(0).getContentType());
				System.out.println("Body part :" + multiMsg.getBodyPart(1).getContentType());
				System.out.println("Body part0 Disposition:" + multiMsg.getBodyPart(0).getDisposition());
				System.out.println("Body part1 Disposition:" + multiMsg.getBodyPart(1).getDisposition());
				System.out.println("Body part1 Disposition:" + multiMsg.getBodyPart(1).getFileName());

				String from = "unknown";
				if (msg.getReplyTo().length >= 1) {
					from = msg.getReplyTo()[0].toString();
				} else if (msg.getFrom().length >= 1) {
					from = msg.getFrom()[0].toString();
				}
				String subject = msg.getSubject();
				System.out.println("Mail Content:::::::::::" + msg.getContent());
				System.out.println("Mail ContentType:::::::::::" + msg.getContentType());

				System.out.println("Saving ... " + subject + " " + from);
				String filename = "c:/temp/" + subject;
				saveParts(msg.getContent(), filename);

			}
		} finally {
			if (folder != null) {
				folder.close(true);
			}
			if (store != null) {
				store.close();
			}
		}
	}

	public static void saveParts(Object content, String filename) throws IOException, MessagingException {
		OutputStream out = null;
		InputStream in = null;
		try {
			if (content instanceof Multipart) {
				Multipart multi = ((Multipart) content);
				int parts = multi.getCount();
				for (int j = 0; j < parts; ++j) {
					MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(j);
					if (part.getContent() instanceof Multipart) {
						// part-within-a-part, do some recursion...
						saveParts(part.getContent(), filename);
					} else {
						String extension = "";
						if (part.isMimeType("text/html")) {
							extension = "html";
						} else {
							if (part.isMimeType("text/plain")) {
								extension = "txt";
							} else {
								// Try to get the name of the attachment
								extension = part.getDataHandler().getName();
							}
							filename = filename + "." + extension;
							System.out.println("... " + filename);
							out = new FileOutputStream(new File(filename));
							in = part.getInputStream();
							int k;
							while ((k = in.read()) != -1) {
								out.write(k);
							}
						}
					}
				}
			}
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.flush();
				out.close();
			}
		}
	}

	public static void main(String args[]) throws Exception {
		ReceiveMailPOP3.doit();
	}
}